package com.mugui.base.client.net.bagsend;


import com.mugui.base.client.net.bean.NetBag;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;


public class WSUtil {


	@Getter
	@Setter
	private static  boolean isPong=false;


	public static void ws(String serverUrl, HashMap<String, String> sessionhead, NetBag bag, WsHandle wsHandle) {
		if (wsHandle.getClient(serverUrl) == null) {
			synchronized (WSUtil.class) {
				if (wsHandle.getClient(serverUrl) == null) {
					wsHandle.init(serverUrl);
					/*if(wsHandle.getClient(serverUrl)==null){
						throw new RuntimeException("连接失败");
					}
					if(wsHandle.getClient(serverUrl).isEmpty()){
						throw new RuntimeException("无可用链接");
					}*/
				}
			}
		}
		if(isPong){
			wsHandle.getClient(serverUrl).sendPongMessage(bag.getSession(),bag.toString());
		}else {
			wsHandle.getClient(serverUrl).sendMessage(bag.toString());
		}
	}


	private static HashMap<String, NetCall> wsNetCalls = new HashMap<>();

	public static NetCall getWsNetCall(String id){
		return wsNetCalls.get(id);
	}
	public static NetCall subNetCall(String func){
		NetCall netCall=new NetCall(func);
		wsNetCalls.put(netCall.getId(),netCall);
		return netCall;
	}

	public static NetCall unsubNetCall(String id) {
		synchronized (wsNetCalls) {
			return wsNetCalls.remove(id);
		}
	}

	public static boolean isRunningTask(){
		return !wsNetCalls.isEmpty();
	}

}
